module.exports = app => {
    const express = require('express');
    const router = express.Router();
    const jwt = require('jsonwebtoken');
    const assert = require('http-assert');
    const admin = require('../../model/Admin');

    //const Category = require('../../model/Category');

    router.post('/', async (req, res) => {
        const model = await req.Model.create(req.body)
        res.send(model)
    });

    router.get('/list', async (req, res) => {
        const queryOption = {};
        if (req.Model.modelName === 'Category') {
            queryOption.populate = 'parent';
        }
        const items = await req.Model.find().setOptions(queryOption).limit(100)
        res.send(items)
    });

    router.get('/:id', async (req, res) => {
        const model = await req.Model.findById(req.params.id);
        res.send(model)
    });

    router.put('/:id', async (req, res) => {
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
        res.send(model)
    });

    router.delete('/:id', async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id, req.body);
        res.send({
            success: true
        })
    });

    // 登录校验中间件
    const auth = require('../../middleware/Auth');

    const resource = require('../../middleware/Resource');

    app.use('/admin/api/rest/:resource', auth(), resource(), router);

    // 图片上传
    const multer = require('multer');
    const upload = multer({
        dest: __dirname + '/../../uploads' // 上传路径
    })
    app.post('/admin/api/upload', auth(), upload.single('file'), async (req, res) => {
        const file = req.file;
        // 返回url地址
        file.url = `http://localhost:3000/uploads/${file.filename}`;
        res.send(file)
    })

    app.post('/admin/api/login', async (req, res) => {
        const { username, password } = req.body;
        // 根据用户名查找用户
        const data = await admin.findOne({ username }).select('+password');
        assert(data, 200, '用户不存在');

        // 验证密码
        const bcrypt = require('bcryptjs');
        const check = bcrypt.compareSync(password, data.password);
        assert(check, 200, '密码不正确');

        // 生成token,返回数据
        let token = jwt.sign({ id: data._id }, app.get('secret'));
        res.send({
            status: 'success',
            token
        })
    })

    app.use(async (err, req, res, next) => {
        res.status(err.statusCode || 200).send({
            status: 'error',
            msg: err.message
        })
    })
}
